#ifndef _NET_WORK_INTER_FACE_H_
#define _NET_WORK_INTER_FACE_H_
#include "global_def.h"
#include "bksevent.h"
#include "dispatchtaskservice.h"
#include "logger.h"

#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>

#include <event.h>
#include <event2/event.h>
#include <event2/listener.h>
#include <event2/bufferevent.h>

#include <queue>
#include <ostream>
#include <memory>

#include "ngx_mem_pool.h"

#include "iniconfig.h"

#define HEADER_TAG "FBEB"
#define HEADER_TAG_LEN strlen(HEADER_TAG)
#define EVENT_ID_LEN 2
#define HEADER_TOTAL_LEN 10

enum class SESSION_STATUS
{
    SS_REQUEST = 0, 
    SS_RESPONSE
};

enum class MESSAGE_STATUS
{
    MS_READ_HEADER = 0,
    MS_READ_HEADER_DONE,
    MS_READ_MESSAGE,
    MS_READ_DONE,
    MS_SENDING,
    MS_SEND_DONE
};

typedef struct _ConnectSession{
    
    char ip[32];

    SESSION_STATUS stat;

    evutil_socket_t fd;
    u16 eid;
    struct bufferevent *bev;

    BKSEvent *reqev;
    MESSAGE_STATUS reqev_stat;

    BKSEvent *rspev;
    MESSAGE_STATUS rspev_stat;

    u32 read_header_len;
    u32 header_len;
    char _header_buf[HEADER_TOTAL_LEN + 1];

    u32 read_msg_len;
    u32 msg_len;
    char *_read_msg_buf;

    u32 write_msg_len;
    char *_write_msg_buf;

    ngx_mem_pool *_pool;

}ConnSession;

class NetWorkInterface{
public:
    NetWorkInterface();
    virtual ~NetWorkInterface();

    BOOL start(short port);
    void stop();

    static void listener_cb(struct evconnlistener *listener, evutil_socket_t sock, struct sockaddr *addr, int len, void *arg);
    static void readCallback(struct bufferevent *bev, void *ctx);
    static void writeCallback(struct bufferevent *bev, void *ctx);
    static void eventCallback(struct bufferevent *bev, short events, void *ctx);

    void network_event_dispatch();

    void handleAllRspEvents();

    void send_rsp_message(void *arg);
    
    static void _free(ConnSession *cs);

private:
    static struct evconnlistener *listener;
    static struct event_base *base;
    std::queue<BKSEvent*> _rsp_evs_queue;
    static std::shared_ptr<IniConfig> ini_ptr;
    // static ngx_mem_pool *_pool;
};
#endif